<script setup lang="ts">
import F_list, {type filterGroupType} from "@/components/admin/f_list.vue";
import type {columnType} from "@/components/admin/f_list.vue";
import {userLoginListApi, type userLoginListType, userLoginLoseApi, userLoginAdminLoseApi} from "@/api/user_api";
import {UAParser} from 'ua-parser-js';
import {Message} from "@arco-design/web-vue";
import {ref} from "vue";
import {userStorei} from "@/stores/user_store";

const store = userStorei()
const columns: columnType[] = [
  {title: "ID", dataIndex: 'id'},
  {title: "ip(地址)", slotName: 'ip'},
  {title: "User-Agent", slotName: 'ua'},
  {title: "本机", slotName: 'user'},
  {title: "登录时间", dataIndex: 'createdAt', type: "date", dateFormat: "datetime"},
  {title: "操作", slotName: 'action'},
]

function getUaInfo(record: userLoginListType) {
  const obj = UAParser(record.ua)
  if (obj.os.name && obj.browser.name) {
    return [obj.os.name, obj.browser.name]
  }
  return []
}

const fListRef = ref()

async function lose(record: userLoginListType) {
  const res = await userLoginLoseApi(record.id)
  if (res.code) {
    Message.error(res.msg)
    return
  }
  Message.success(res.msg)
  fListRef.value.getList()
}


</script>

<template>
  <div class="user_login_list_view">
    <f_list
        ref="fListRef"
        :url="userLoginListApi"
        :params="{type: 1}"
        no-add
        no-edit
        no-delete
        @edit="lose"
        :columns="columns">
      <template #action_left="{record}:{record: userLoginListType}">
        <a-popconfirm v-if="store.userInfo.token === record.token" @ok="lose(record)" content="确定要下线当前设备的登录状态吗？">
          <a-button type="primary" status="danger">下线</a-button>
        </a-popconfirm>
        <a-button v-else @click="lose(record)" type="primary" status="danger">下线</a-button>
      </template>
      <template #ua="{record}:{record: userLoginListType}">
        <template v-if="getUaInfo(record).length">
          <img class="os iconImag" :src="`/icons/${getUaInfo(record)[0].toLowerCase()}.svg`" alt="">
          <img class="browser iconImag" :src="`/icons/${getUaInfo(record)[1].toLowerCase()}.svg`" alt="">
        </template>
        <span v-else>{{ record.ua }}</span>
      </template>
      <template #ip="{record}:{record: userLoginListType}">
        {{ record.ip }}({{ record.addr }})
      </template>
      <template #user="{record}:{record: userLoginListType}">
        <a-switch :model-value="store.userInfo.token === record.token"></a-switch>
      </template>
    </f_list>
  </div>
</template>

<style lang="less">
.user_login_list_view {
  .iconImag {
    width: 20px;
    height: 20px;

    &.browser {
      margin-left: 5px;
    }
  }
}
</style>